package com.example.administrator.runbook.findfragment.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.runbook.R;
import com.example.administrator.runbook.findfragment.adapter.MyListViewBaseAdapter;
import com.example.administrator.runbook.findfragment.model.BookList;
import com.example.administrator.runbook.findfragment.model.BookListItem;
import com.example.administrator.runbook.findfragment.model.MessageToAfterClassify;
import com.example.administrator.runbook.findfragment.network.GetFindClassifyService;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AfterClassifyActivity extends BaseActivity implements View.OnClickListener, AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    public static final String MESSAGEINFOR = "MessageSendToAfterClassify";
    private MessageToAfterClassify mMessageToAfter;
    private LinearLayout mClassify;
    private LinearLayout mTitle;
    private String mTitle1;
    private RelativeLayout mAnimAll;
    private Drawable mDrawable;
    private ImageView mWaitAnim;
    private List<String> mMins;
    private List<String> mTitles;
    private String memoryType;
    private String memoryMinor;
    private GetFindClassifyService mGetFindClassifyService;
    private String mName;
    private int start;
    private int limit;
    private List<BookListItem> mBookListItems;
    private boolean isAdd;
    private ListView mList;
    private MyListViewBaseAdapter mAdapter;
    private LinearLayout mShowHid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_after_classify);
        mTitles = new ArrayList<>();
        mBookListItems = new ArrayList<>();
        mClassify = (LinearLayout) findViewById(R.id.activity_after_classify_classify);
        mTitle = (LinearLayout) findViewById(R.id.activity_find_classify_classifyTitle);
        mAnimAll = (RelativeLayout) findViewById(R.id.activity_find_classify_wait);
        mWaitAnim = (ImageView) findViewById(R.id.activity_find_classify_wait_img);
        mShowHid = (LinearLayout) findViewById(R.id.activity_find_classify_show_hide);
        mList = (ListView) findViewById(R.id.activity_find_classify_item);
        mAdapter = new MyListViewBaseAdapter(this, mBookListItems);
//        mShowHid.setVisibility(View.GONE);
        mList.setAdapter(mAdapter);
        mTitle1 = mMessageToAfter.getTitle();
        mMins = mMessageToAfter.getMins();
        startAnim();
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://api.zhuishushenqi.com");
        builder.addConverterFactory(ScalarsConverterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.newThread()));
        Retrofit build = builder.build();
        mGetFindClassifyService = build.create(GetFindClassifyService.class);
        memoryType = "hot";
        memoryMinor = "";
        start = 0;
        limit = 20;
        getDataFromNetwork();
        initView();
        mList.setOnScrollListener(this);
        mList.setOnItemClickListener(this);
    }

    private void initView() {
        if ("男生".equals(mTitle1) || "女生".equals(mTitle1)) {
            mTitles.add("热门");
            mTitles.add("新书");
            mTitles.add("好评");
            mTitles.add("完结");
            mTitles.add("包月");
        }
        int size = mTitles.size();
        if (size != 0) {
            mClassify.setVisibility(View.VISIBLE);
            for (int i = 0; i < size; i++) {
                TextView view = new TextView(this);
                view.setId(i);
                view.setOnClickListener(this);
                view.setText(mTitles.get(i));
                if (i == 0){
                    view.setTextColor(Color.RED);
                }
                view.setLayoutParams(new LinearLayout.LayoutParams(100, ViewGroup.LayoutParams.MATCH_PARENT));
                view.setGravity(Gravity.CENTER);
                mClassify.addView(view);
            }
        }
        int i = mMins.size();
        if (i != 0){
            mTitle.setVisibility(View.VISIBLE);
            int section = mTitles.size();
            for (int j = 0; j < i + 1; j++) {
                TextView view = new TextView(this);
                final int id = j + section;
                view.setId(id);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setTitleClick(((TextView) v), id);
                    }
                });
                if (j == 0) {
                    view.setText("全部");
                    view.setLayoutParams(new LinearLayout.LayoutParams(100, ViewGroup.LayoutParams.MATCH_PARENT));
                } else {
                    String text = mMins.get(j - 1);
                    view.setText(text);
                    view.setLayoutParams(new LinearLayout.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT));
                }
                if (j == 0){
                    view.setTextColor(Color.RED);
                }
                view.setGravity(Gravity.CENTER);
                mTitle.addView(view);
            }
        }
    }

    private void setTitleClick(TextView v, int id) {
        isAdd = false;
        limit = 20;
        start = 0;
        int count = mTitle.getChildCount();
        for (int i = 0; i < count; i++){
            TextView childAt = (TextView) mTitle.getChildAt(i);
            if (i != id) {
                childAt.setTextColor(Color.GRAY);
            }
        }
        v.setTextColor(Color.RED);
        String trim = v.getText().toString().trim();
        if (trim.equals("全部")){
            memoryMinor = "";
        } else {
            memoryMinor = trim;
        }
        getDataFromNetwork();
        Log.d("Hello", "onClick: " +  v.getText().toString());
    }

    @Override
    public void setToolBar(Toolbar toolbar) {
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    public void setToolBarTitleText(TextView toolBarTitleText) {
        if (toolBarTitleText != null) {
            mMessageToAfter = getIntent().getParcelableExtra(MESSAGEINFOR);
            if (mMessageToAfter != null) {
                mName = mMessageToAfter.getName();
                toolBarTitleText.setText(mName);
            }
        }
    }

    @Override
    public void setBackImg(ImageView backImg) {
        if (backImg != null) {
            backImg.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_find_classify_goBack_img:
                finish();
                break;
            case 0:
                setClassifyClick((TextView) v, 0);
                break;
            case 1:
                setClassifyClick((TextView) v, 1);
                break;
            case 2:
                setClassifyClick((TextView) v, 2);
                break;
            case 3:
                setClassifyClick((TextView) v, 3);
                break;
            case 4:
                setClassifyClick((TextView) v, 4);
                break;
            case R.id.activity_find_classify_show_hide:
                int mClassifyVisibility = mClassify.getVisibility();
                int mTitleVisibility = mTitle.getVisibility();
                int mShowHidVisibility = mShowHid.getVisibility();
                if (mClassifyVisibility == View.GONE && mTitleVisibility == View.GONE && mShowHidVisibility == View.VISIBLE){
                    mShowHid.setVisibility(View.GONE);
                    if (mTitles.size() != 0) {
                        mClassify.setVisibility(View.VISIBLE);
                    }
                    if (mMins.size() != 0) {
                        mTitle.setVisibility(View.VISIBLE);
                    }
                }
                break;
        }
    }

    private void setClassifyClick(TextView v, int index) {
        isAdd = false;
        limit = 20;
        start = 0;
        int count = mClassify.getChildCount();
        for (int i = 0; i < count; i++){
            TextView childAt = (TextView) mClassify.getChildAt(i);
            if (i != index) {
                childAt.setTextColor(Color.GRAY);
            }
        }
        v.setTextColor(Color.RED);
        String trim = v.getText().toString().trim();
        switch (trim) {
            case "热门":
                memoryType = "hot";
                break;
            case "新书":
                memoryType = "new";
                break;
            case "好评":
                memoryType = "reputation";
                break;
            case "完结":
                memoryType = "over";
                break;
            case "包月":
                memoryType = "monthly";
                break;
        }
        getDataFromNetwork();
        Log.d("Hello", "onClick: " +  v.getText().toString());
    }

    public void getDataFromNetwork() {
        String gender = null;
        switch (mTitle1) {
            case "男生":
                gender = "male";
                break;
            case "女生":
                gender = "female";
                break;
            case "出版":
                gender = "press";
                break;
        }
        String limit = String.valueOf(this.limit);
        String start = String.valueOf(this.start);
        Observable<BookList> male =
                mGetFindClassifyService.getBookList(gender, memoryType, mName, memoryMinor, start, limit);
        male.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BookList>() {
                    @Override
                    public void onCompleted() {
                        int visibility = mAnimAll.getVisibility();
                        if (visibility == View.VISIBLE) {
                            stopAnim();
                        }
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(AfterClassifyActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BookList list) {
                        if (isAdd) {
                            mBookListItems.addAll(list.getListItems());
                        } else {
                            mBookListItems.clear();
                            mBookListItems.addAll(list.getListItems());
                        }
                    }
                });
    }

    private void startAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.start();
        }
    }

    private void stopAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.stop();
        }
        mAnimAll.setVisibility(View.GONE);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        Log.d("Hello", "onScroll: firstVisibleItem = " + firstVisibleItem + ", visibleItemCount = " + visibleItemCount + ", totalItemCount = " + totalItemCount);
        if (firstVisibleItem >= 1) {
            if (mTitles.size() != 0) {
                mClassify.setVisibility(View.GONE);
            }
            if (mMins.size() != 0){
                mTitle.setVisibility(View.GONE);
            }
            mShowHid.setVisibility(View.VISIBLE);
        } else if (firstVisibleItem == 0) {
            if (mTitles.size() != 0) {
                mClassify.setVisibility(View.VISIBLE);
            }
            if (mMins.size() != 0){
                mTitle.setVisibility(View.VISIBLE);
            }
            mShowHid.setVisibility(View.GONE);
        }
        if (firstVisibleItem + visibleItemCount >= totalItemCount){
            start = start + 20;
            isAdd = true;
            getDataFromNetwork();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String s = mBookListItems.get(position).getId();
        Log.d("Hello", "onScroll: s = " + s);
        Intent intent = new Intent(this, BookItemActivity.class);
        intent.putExtra("BookId", s);
        startActivity(intent);
    }
}